package com.qf.controller;
/*
 *@Description:
 *@author:刘哥
 *@Date:16:23 2022/8/13
 */

import cn.dsna.util.images.ValidateCode;
import com.qf.pojo.TbAddress;
import com.qf.pojo.TbUser;
import com.qf.service.AddressService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;
import com.qf.utils.MD5Utils;
import com.qf.utils.StringConstans;
import com.qf.utils.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 * projectName:xiaomi
 * author:刘哥
 * time:2022/8/13 16:23
 * description:
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {
//    userservlet?method=register
    public String register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");


        if (StringUtil.isEmpty(username)){
            request.setAttribute("registerMsg", "用户名不可为空");
            return "/register.jsp";
        }
        if (StringUtil.isEmpty(password)||password.length()<6||password.length()>=16){
            request.setAttribute("registerMsg", "密码格式不正确");
            return "/register.jsp";
        }
        if (!email.matches(StringConstans.EMAILREGE)){
            request.setAttribute("registerMsg", "邮箱格式不正确");
            return "/register.jsp";
        }
        if (StringUtil.isEmpty(gender)){
            request.setAttribute("registerMsg", "性别不可为空");
            return "/register.jsp";
        }
        try {
            TbUser user=new TbUser();
            user.setUsername(username);
            user.setPassword(MD5Utils.md5(password));
            user.setEmail(email);
            user.setGender(gender);
            user.setFlag(0L);
            user.setRole(1L);
            user.setCode(new Date().toString());
            UserService userService=new UserServiceImpl();
            userService.add(user);
            return "registerSuccess.jsp";
        } catch (Exception e) {
            return "redirect:/register.jsp";
        }

    }

//    userservlet?method=login
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("code");
        String auto = request.getParameter("auto");
        if (StringUtil.isEmpty(username)){
            request.setAttribute("msg", "用户密码不可为空");
            return "/login.jsp";
        }
        if (StringUtil.isEmpty(password)){
            request.setAttribute("msg", "用户密码不可为空");
            return "/login.jsp";
        }
        if (StringUtil.isEmpty(vcode)){
            request.setAttribute("msg", "验证码不可为空");
            return "/login.jsp";
        }

        String pagecode = (String) request.getSession().getAttribute("pagecode");
        request.getSession().removeAttribute("pagecode");
        if (!vcode.equalsIgnoreCase(pagecode)){
            request.setAttribute("msg", "验证码不正确");
            return "/login.jsp";
        }
        UserService userService=new UserServiceImpl();
        TbUser user = userService.selectByUser(username);
        password=MD5Utils.md5(password);
        if(password.equals(user.getPassword())){
            if (auto != null) {//用户想自动登录
//                创建cookie，保存用户信息
                String userinfo = username + "#" + password;
//                加密
                userinfo = Base64Utils.encode(userinfo);
                Cookie cookie = new Cookie("userinfo", userinfo);
//                设置有效路径
                cookie.setPath(request.getContextPath());
//                cookie保存的有效期  秒*分*小时*天数
                cookie.setMaxAge(60 * 60 * 24 * 14);
//                设置httpponly
                cookie.setHttpOnly(true);
//                回写添加到浏览器cookie
                response.addCookie(cookie);
            }
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
//                更新登录时间
            CompletableFuture.runAsync(()->{
                userService.upDateLoginTime(user.getId());
            });
            return "redirect:/index.jsp";

        }else {
            request.setAttribute("msg", "用户密码不正确");
            return "/login.jsp";
        }

    }


    public void checkUserName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("username = " + username);
        if (username == null||username.length()==0) {
            response.getWriter().write("1");
            return;
        }
        UserService userSercice=new UserServiceImpl();
        boolean b = userSercice.checkUserName(username);
        if (b) {
            response.getWriter().write("0");
            return;
        }
        response.getWriter().write("2");
        return;

    }

    public void checkCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String vcode = request.getParameter("vcode");
        System.out.println("vcode = " + vcode);
//        if (code == null||code.length()==0) {
//            response.getWriter().write("1");
//            return null;
//        }
        String code = (String) request.getSession().getAttribute("code");
        if (vcode.equalsIgnoreCase(code)) {
            response.getWriter().write("0");
            return;
        }
        response.getWriter().write("1");
        return;
    }
    public void code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ValidateCode validateCode=new ValidateCode(100,40,4,10);
        validateCode.createCode();
        String code = validateCode.getCode();
//        System.out.println("code = " + code);
        request.getSession().setAttribute("pagecode", code);
        validateCode.write(response.getOutputStream());
    }

//    public String  addAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//
//        TbUser user = (TbUser) request.getSession().getAttribute("user");
//        if (user == null) {
//            return "redirect:/login.jsp";
//        }
//
//        String name = request.getParameter("name");
//        String phone = request.getParameter("phone");
//        String detail = request.getParameter("detail");
//        System.out.println("detail = " + detail);
//        System.out.println("name = " + name);
//        if(StringUtil.isEmpty(name)){
//            request.setAttribute("msg", "收件人不可为空");
//            return "self_info.jsp";
//        }
//        if(StringUtil.isEmpty(phone)){
//            request.setAttribute("msg", "收件人不可为空");
//            return "self_info.jsp";
//        }
//        if(StringUtil.isEmpty(detail)){
//            request.setAttribute("msg", "收件人不可为空");
//            return "self_info.jsp";
//        }
//        AddressService addressService=new AddressServiceImpl();
//        TbAddress tbAddress=new TbAddress();
//        tbAddress.setName(name);
//        tbAddress.setPhone(phone);
//        tbAddress.setDetail(detail);
//        tbAddress.setUid(user.getId());
//        tbAddress.setLevel(0);
//        addressService.add(tbAddress);
//
//
//        return "redirect:/address?method=getAddress";
//    }
}
